package com.wisdytech.ccdserver.common.utils;

import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.parser.CCJSqlParserManager;
import net.sf.jsqlparser.util.TablesNamesFinder;

import java.io.StringReader;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * description
 *
 * @author Hehaifeng
 * @module
 * @date 2022/3/25 15:32
 */

public class CommonUtil {

    private static CCJSqlParserManager pm = new CCJSqlParserManager();

    private static String REG = "“\\w+”";

    /**
     * 获取sql中的表名
     * @param sql insert或update sql
     * @return 表名
     */
    public static String getTableName(String sql) {
        StringBuilder errorMessage = new StringBuilder();
        try {
            net.sf.jsqlparser.statement.Statement statements = pm.parse(new StringReader(sql));
            TablesNamesFinder tablesNamesFinder = new TablesNamesFinder();
            List<String> tablenames = tablesNamesFinder.getTableList(statements);
            if (!tablenames.isEmpty()) {
                errorMessage.append(tablenames.get(0));
            }
        } catch(JSQLParserException e) {
            e.printStackTrace();
        }
        return errorMessage.toString();
    }

    /**
     * 获取超长错误中的字段值
     * @param message 超长错误信息
     * @return 字段值
     */
    public static String getFiledName(String message) {
        String filedName = null;
        if (message.contains("'") && message.split("'").length > 1) {
            filedName = message.split("'")[1];
        }
        return filedName;
    }


    public static String getSqlServerFiledName(String message){
        Pattern p = Pattern.compile(REG);
        Matcher m = p.matcher(message);
        if(m.find()){
            return m.group().replaceAll("“","").replaceAll("”","");
        }
        return null;
    }

}
